import { useCallback, useEffect, useState } from 'react';
import {
  Card,
  Button,
  Input,
  Modal,
  Form,
  message,
  Space,
  Typography,
  InputNumber,
  Upload,
  Row,
  Col,
  Image,
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ShopOutlined,
} from '@ant-design/icons';
import type { RcFile, UploadFile } from 'antd/es/upload/interface';
import {
  addShopGoods,
  deleteShopGoods,
  getGoodsList,
  updateShopGoods,
  uploadImage,
} from '@/api/shop';

const { Title, Text } = Typography;
const { TextArea } = Input;

/**
 * 商品管理界面
 */
const Business = () => {
  const [form] = Form.useForm();
  const [products, setProducts] = useState<ShopGoods[]>([]);
  const [searchText, setSearchText] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<ShopGoods | null>(null);
  const [imageUrl, setImageUrl] = useState<string>();
  const [loading, setLoading] = useState(false);

  const fetchProducts = async () => {
    const res = await getGoodsList({ page: 1, limit: 100 });
    setProducts(res.data.list);
  };

  useEffect(() => {
    fetchProducts();
  }, []);

  // 新增商品
  const createProduct = async (values: Omit<ShopGoods, 'id' | 'created_time'>) => {
    await addShopGoods({
      ...values,
      publish_id: editingProduct?.publish_id || 1,
    });
    message.success('创建成功');
    fetchProducts();
  };

  // 更新商品
  const updateProduct = async (values: ShopGoods) => {
    await updateShopGoods({
      ...editingProduct,
      ...values,
      publish_id: editingProduct?.publish_id || 1,
    });
    message.success('更新成功');
    fetchProducts();
  };

  // 删除商品
  const deleteProduct = async (id: number) => {
    await deleteShopGoods(id);
    message.success('删除成功');
    fetchProducts();
  };

  // 模拟数据操作
  const handleAdd = (values: Omit<ShopGoods, 'id' | 'created_time' | 'publish_id'>) => {
    createProduct({
      ...values,
      publish_id: 1,
    });
    message.success('创建成功');
  };

  // 更新商品
  const handleEdit = (values: ShopGoods) => {
    if (!editingProduct) return;
    updateProduct(values);
  };

  // 删除商品
  const handleDelete = (id: number) => {
    deleteProduct(id);
  };

  const handleSearch = useCallback((value: string) => {
    setSearchText(value);
  }, []);

  const showModal = (product?: ShopGoods) => {
    if (product) {
      setEditingProduct(product);
      form.setFieldsValue(product);
      setImageUrl(product.img);
    } else {
      setEditingProduct(null);
      form.resetFields();
      setImageUrl(undefined);
    }
    setIsModalVisible(true);
  };

  // 点击确定按钮
  const handleModalOk = () => {
    form.validateFields().then((values) => {
      if (editingProduct) {
        handleEdit(values);
      } else {
        handleAdd(values);
      }
      setIsModalVisible(false);
      form.resetFields();
      setImageUrl(undefined);
    });
  };

  // 上传前检查文件
  const beforeUpload = (file: RcFile) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      message.error('图片必须小于10MB!');
    }
    return isImage && isLt2M;
  };

  // 处理文件上传变化
  const handleChange = async (info: { file: UploadFile }) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }

    if (info.file.originFileObj) {
      try {
        const formData = new FormData();
        formData.append('file', info.file.originFileObj);
        // 调用上传接口
        const res = await uploadImage(formData);
        if (res.code === 200) {
          setLoading(false);
          setImageUrl(res.data);
          form.setFieldsValue({ img: res.data });
          message.success('上传成功');
        } else {
          setLoading(false);
          message.error('上传失败');
        }
      } catch (error) {
        setLoading(false);
        message.error('上传出错');
        console.error('上传错误:', error);
      }
    }
  };

  const uploadButton = (
    <div>
      {loading ? <div className="animate-spin">加载中</div> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );

  const filteredProducts = products.filter(
    (product) =>
      product.goods_name.toLowerCase().includes(searchText.toLowerCase()) ||
      product.description.toLowerCase().includes(searchText.toLowerCase()) ||
      product.origin.toLowerCase().includes(searchText.toLowerCase())
  );

  return (
    <div className="p-6">
      <Card>
        <div className="flex justify-between items-center mb-6">
          <div className="flex items-center">
            <ShopOutlined className="text-2xl text-emerald-600 mr-3" />
            <Title
              level={2}
              className="!mb-0"
            >
              商品管理
            </Title>
          </div>
          <Space size="large">
            <Input.Search
              placeholder="搜索商品名称/描述/产地"
              prefix={<SearchOutlined className="text-gray-400" />}
              value={searchText}
              onChange={(e) => handleSearch(e.target.value)}
              allowClear
              className="w-64"
            />
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => showModal()}
              className="bg-emerald-600 hover:bg-emerald-700"
            >
              新增商品
            </Button>
          </Space>
        </div>

        <Row gutter={[16, 16]}>
          {filteredProducts.map((product) => (
            <Col
              xs={24}
              sm={12}
              md={8}
              lg={6}
              key={product.id}
            >
              <Card
                style={{ width: '100%', height: '100%', maxWidth: 350 }}
                hoverable
                cover={
                  <div className="relative h-48 bg-gray-100 overflow-hidden">
                    <Image
                      style={{ objectFit: 'cover', width: '100%', height: '100%' }}
                      alt={product.goods_name}
                      src={product.img}
                      className="object-cover w-full h-full"
                    />
                  </div>
                }
              >
                <div className="p-2">
                  <Title
                    level={4}
                    className="!mb-0"
                  >
                    {product.goods_name}
                  </Title>
                  <Text className="text-sm text-gray-500">{product.description}</Text>
                  <Text className="text-sm text-gray-500">{product.origin}</Text>
                  <Text className="text-sm text-gray-500">{product.goods_price.toFixed(2)}</Text>
                </div>
                <div className="mt-2 flex justify-between items-center">
                  <Button
                    type="primary"
                    icon={<EditOutlined />}
                    onClick={() => showModal(product)}
                    className="bg-emerald-600 hover:bg-emerald-700"
                  >
                    编辑
                  </Button>
                  <Button
                    type="primary"
                    icon={<DeleteOutlined />}
                    onClick={() => handleDelete(product.id)}
                    className="bg-red-600 hover:bg-red-700"
                  >
                    删除
                  </Button>
                </div>
              </Card>
            </Col>
          ))}
        </Row>
      </Card>

      <Modal
        title={editingProduct ? '编辑商品' : '新增商品'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={editingProduct || {}}
        >
          <Form.Item
            name="goods_name"
            label="商品名称"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="goods_price"
            label="商品价格"
            rules={[{ required: true, message: '请输入商品价格' }]}
          >
            <InputNumber />
          </Form.Item>
          <Form.Item
            name="description"
            label="商品描述"
            rules={[{ required: true, message: '请输入商品描述' }]}
          >
            <TextArea />
          </Form.Item>
          <Form.Item
            name="origin"
            label="商品产地"
            rules={[{ required: true, message: '请输入商品产地' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="img"
            label="商品图片"
            rules={[{ required: true, message: '请上传商品图片' }]}
          >
            <Upload
              name="file"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              customRequest={({ onSuccess }) => {
                // 使用自定义上传方式，让handleChange处理实际上传
                setTimeout(() => {
                  onSuccess?.({}, new XMLHttpRequest());
                }, 0);
              }}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <div style={{ width: '100%', height: '100%' }}>
                  <img
                    src={imageUrl}
                    alt="avatar"
                    style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                  />
                </div>
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Business;
